const path = require('path')

const requireDirectory = require('require-directory')
const Router = require('koa-router')

class InitCore {
  /**
   * @param {*} app 
   * @description 入口方法 app参数为koa实例
   */
  static init (app) {
    InitCore.app = app
    InitCore.loadRouter()
    InitCore.loadConfig()
    InitCore.loadException()
  }

  /**
   * @description 自动导入并注册koa路由
   */
  static loadRouter () {
    const apiDir = process.cwd() + '/app/api'
    requireDirectory(module, apiDir, {
      visit: whenLoadModule
    })

    function whenLoadModule (obj) {
      if (obj instanceof Router) InitCore.app.use(obj.routes())
    }
  }

  /**
   * @description 导入配置文件并添加在全局global上
   */
  static loadConfig () {
    const configPath = process.cwd() + '/config/config.js'
    global.config = require(configPath)
  }
  /**
   * @description 导入异常类并添加在global上
   */
  static loadException () {
    const errors = require('./exception')
    global.errs = errors
  }
}

module.exports = InitCore
